<template>
  <div class="app-container">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()" size="mini">
            <el-form-item label="合同编号">
                <el-input v-model="queryParams.contractNo" :placeholder="$t('contract.contractNo')" clearable/>
            </el-form-item>
            <el-form-item label="合同名称">
                <el-input v-model="queryParams.contractName" :placeholder="$t('contract.contractName')" clearable/>
            </el-form-item>
            <el-form-item label="合同所属企业">
                <el-select
                        v-model="queryParams.clientId"
                        filterable
                        remote
                        clearable
                        reserve-keyword
                        placeholder="请输入合同所属企业名称关键字"
                        :remote-method="remoteMethod"
                        :loading="loading"
                        style="width: 320px">
                    <el-option
                            v-for="item in companyList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" :picker-options="pickerOptions" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button @click="getDataList()">{{ $t('query') }}</el-button>
                <el-button type="primary" @click="exportExcel">{{ $t('export') }}</el-button>
            </el-form-item>
        </el-form>
        <el-table
                id="integration-table"
                size="mini"
                v-loading="dataListLoading"
                :data="dataList"
                border
                stripe
                style="width: 100%;">
            <el-table-column prop="contractNo" :label="$t('contract.contractNo')" header-align="center" align="center"/>
            <el-table-column prop="contractName" :label="$t('contract.contractName')" header-align="center"
                             align="center"/>
            <el-table-column prop="amount" :label="$t('contract.amount')" header-align="center" align="center"/>
            <el-table-column prop="contractAmount" :label="$t('contract.contractAmount')" header-align="center"
                             align="center"/>
            <el-table-column prop="clientName" label="合同所属企业" header-align="center" align="center"/>
            <el-table-column prop="customerName" :label="$t('contract.customerName')" header-align="center"
                             align="center"/>
            <el-table-column prop="createName" :label="$t('contract.createName')" header-align="center" align="center"/>
            <el-table-column prop="createTime" :label="$t('createTime')" header-align="center" align="center"/>
        </el-table>
        <!-- 分页 -->
        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.current"
                :limit.sync="queryParams.size"
                @pagination="getDataList"/>

        <el-dialog :visible.sync="visible" :title="$t('export')" :close-on-click-modal="false"
                   :close-on-press-escape="false" width="30%">
            <el-form v-model="exportForm" label-width="120px">
                <el-form-item label="模板">
                    <el-select v-model="exportForm.template" filterable placeholder="请选择"
                               @change="initPlaceholderOptions" clearable>
                        <el-option-group
                                v-for="group in templateOptions"
                                :key="group.label"
                                :label="group.label">
                            <el-option
                                    v-for="item in group.options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="导出字段">
                    <el-tree
                            :data="placeholderOptions"
                            :props="treeProps"
                            show-checkbox
                            @check-change="handleCheckChange">
                    </el-tree>
                </el-form-item>
                <el-form-item label="导出时间">
                    <el-form-item>
                        <el-date-picker
                                v-model="exportDateValue"
                                @change="changeExportDate"
                                type="daterange"
                                align="right"
                                unlink-panels
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="yyyy-MM-dd"
                                :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                </el-form-item>
            </el-form>
            <template slot="footer">
                <el-button type="primary" @click="exportData">{{ $t('confirm') }}</el-button>
            </template>
        </el-dialog>
  </div>
</template>

<script>
    import {contractInfoStatisticsPage} from "@/api/zfw/statistic/statistic";

    export default {
        data() {
            return {
                dataList: [],
                loading: false,
                dataListLoading:false,
                dataForm: {},
                dateValue: [],
                companyList: [],
                exportDateValue: [],
                // 日期范围
                dateRange: [],
                // 总条数
                total: 0,
                // 查询参数
                queryParams: {
                    current: 1,
                    size: 10,
                    contractNo: null,
                    contractName: null,
                    status: null,
                    amount: null,
                    contractAmount: null,
                    clientId: null,
                    clientName: null,
                    customerName: null,
                    createTime: null,
                },
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', [start, end])
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                            picker.$emit('pick', [start, end])
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date()
                            const start = new Date()
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                            picker.$emit('pick', [start, end])
                        }
                    }]
                },
                visible: false,
                exportForm: {
                    template: '',
                    placeholders: [],
                    startDate: '',
                    endDate: ''
                },
                templateOptions: [
                    {
                        label: '私有模板库',
                        options: []
                    }, {
                        label: '公共模板库',
                        options: []
                    }
                ],
                placeholderOptions: [],
                treeProps: {
                    id: 'id',
                    label: 'placeholderName',
                    children: 'children'
                },
                columns: [
                    {
                        label: '合同编号',
                        prop: 'contractNo'
                    },
                    {
                        label: '合同名称',
                        prop: 'contractName'
                    },
                    {
                        label: '合同金额',
                        prop: 'amount'
                    },
                    {
                        label: '合同付费金额',
                        prop: 'contractAmount'
                    },
                    {
                        label: '合同签署人',
                        prop: 'customerName'
                    },
                    {
                        label: '合同创建人',
                        prop: 'createName'
                    },
                    {
                        label: '合同创建时间',
                        prop: 'createTime'
                    }
                ],
                dynamicColumns: []
            }
        },
        methods: {
            init: function () {
                this.initTemplateOptions()
            },
            getDataList(){
                contractInfoStatisticsPage(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                    this.dataList = response.data.records;
                    this.total = response.data.total;
                    this.loading = false;
                    this.dataListLoading = false;
                });
            },

            // changeDate: function (value) {
            //     if (value === null) {
            //         this.queryItems[2].value = ''
            //         this.queryItems[3].value = ''
            //     } else {
            //         this.queryItems[2].value = value[0]+ ' 00:00:00'
            //         this.queryItems[3].value = value[1]+ ' 23:59:59'
            //     }
            // },
            changeExportDate: function (value) {
                if (value === null) {
                    this.exportForm.startDate = ''
                    this.exportForm.endDate = ''
                } else {
                    this.exportForm.startDate = value[0] + ' 00:00:00'
                    this.exportForm.endDate = value[1] + ' 23:59:59'
                }
            },
            exportData: function () {
                this.dynamicColumns = []
                this.placeholderOptions.forEach(placeholder => {
                    placeholder.children.forEach(children => {
                        this.exportForm.placeholders.forEach(id => {
                            if (children.id === id) {
                                this.dynamicColumns.push({
                                    label: placeholder.placeholderName + '.' + children.placeholderName,
                                    prop: 'contractPlaceholders.' + placeholder.placeholderName + '.' + children.placeholderName
                                })
                            }
                        })
                    })
                })
                let col = this.columns.concat(this.dynamicColumns)
                this.$axios.get('/manager/statistics/exportContractInfoStatistics?templateRecordId=' + this.exportForm.template + '&startDate=' + this.exportForm.startDate + '&endDate=' + this.exportForm.endDate).then(res => {
                    if (res !== null && res !== undefined) {
                        this.$export.excel({
                            columns: col,
                            data: res,
                            title: '合同信息导出'
                        }).then(() => {
                            this.$message({
                                message: '导出表格成功',
                                type: 'success'
                            })
                        })
                    }
                }).catch(() => {
                })
            },
            initTemplateOptions: function () {
                this.$axios.get('/manager/template/templeteList').then(res => {
                    res.forEach(template => {
                        if (template.companyName === '私有模板库') {
                            this.templateOptions[0].options.push({
                                value: template.recordId,
                                label: template.templeteName
                            })
                        } else {
                            this.templateOptions[1].options.push({
                                value: template.recordId,
                                label: template.templeteName
                            })
                        }
                    })
                }).catch(() => {
                })
            },
            initPlaceholderOptions: function (tempateRecordId) {
                this.placeholderOptions = []
                this.exportForm.placeholders = []
                if (tempateRecordId !== '') {
                    this.$axios.get('/manager/template/placeholderTree/' + tempateRecordId).then(res => {
                        this.placeholderOptions = res
                    }).catch(() => {
                    })
                }
            },
            handleCheckChange: function (data, isCheck, isChildrenCheck) {
                if (!(data.id === 0 && !isCheck && isChildrenCheck)) {
                    if (data.id === 0) {
                        if (isCheck) {
                            data.children.forEach(item => this.addPlaceholder(item.id))
                        } else {
                            data.children.forEach(item => this.removePlaceholder(item.id))
                        }
                    } else {
                        if (isCheck) {
                            this.addPlaceholder(data.id)
                        } else {
                            this.removePlaceholder(data.id)
                        }
                    }
                }
            },
            addPlaceholder: function (id) {
                if (this.exportForm.placeholders.indexOf(id) === -1) {
                    this.exportForm.placeholders.push(id)
                }
            },
            removePlaceholder: function (id) {
                this.exportForm.placeholders.forEach((item, index) => {
                    if (item === id) {
                        this.exportForm.placeholders.splice(index, 1)
                    }
                })
            },
            remoteMethod(query) {
                if (query !== '') {
                    this.loading = true
                    this.getCompanyList(query)
                } else {
                    this.companyList = []
                }
            },
            getCompanyList(queryName) {
                return this.$axios.get('/manager/company/page', {
                    params: {
                        order: 'ASC',
                        orderField: 'createTime',
                        current: 1,
                        size: 20,
                        listMode: true,
                        queryItems: 'name,LIKE,' + queryName
                    }
                }).then(res => {
                    this.loading = false
                    this.companyList = res.records
                }).catch(() => {
                })
            },
            //导出表格合同
            // 定义导出Excel表格事件
            exportExcel () {
                /* 从表生成工作簿对象 */
                var wb =this.$XLSX.utils.table_to_book(document.querySelector('#integration-table'))
                /* 获取二进制字符串作为输出 */
                var wbout = this.$XLSX.write(wb, {
                    bookType: 'xlsx',
                    bookSST: true,
                    type: 'array'
                })
                try {
                    // Blob 对象表示一个不可变、原始数据的类文件对象。
                    // Blob 表示的不一定是JavaScript原生格式的数据。
                    // File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
                    // 返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
                    this.$FileSaver.saveAs(
                        new Blob([wbout], { type: 'application/octet-stream' }),
                        // 设置导出文件名称
                        '合同信息统计.xlsx')
                } catch (e) {
                    if (typeof console !== 'undefined') console.log(e, wbout)
                } return wbout
            },
        },
        mounted() {
            this.init();
            this.getDataList();
        }
    }
</script>
